package cn.edu.scut.hsrc.cluster;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.edu.scut.hsrc.bean.Doc;
import cn.edu.scut.hsrc.output.ClusterResult;
import cn.edu.scut.hsrc.output.Label;

/**
 * 站点聚类模块
 * 把检索结果按照来源站点进行组织
 * @author feiyu
 *
 */

public class SiteCluster extends ICluster{
	
	private final Doc [] docs;
	
	public SiteCluster(Doc [] docs) {
		// TODO Auto-generated constructor stub
		this.docs = docs;
	}

	/**
	 * 站点聚类
	 */
	@Override
	public ClusterResult[] doCluster() {
		Map<String, List<Doc>> maps = new HashMap<String, List<Doc>>();
		
		int DOC_NUM = this.docs.length;
		for(int i=0;i<DOC_NUM;i++)
		{
			String site = this.docs[i].getSite();
			List<Doc> tmpDocs = maps.get(site);
			if(tmpDocs == null)
				tmpDocs = new ArrayList<Doc>();
			tmpDocs.add(this.docs[i]);
			maps.put(site, tmpDocs);
		}
		
		//遍历
		List<ClusterResult> results = new ArrayList<ClusterResult>();
		Iterator<Map.Entry<String, List<Doc>>> iterator = maps.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, List<Doc>> entry = iterator.next();
			ClusterResult tmp = new ClusterResult(new Label(entry.getKey(), 0));
			tmp.setDocs(entry.getValue());
			results.add(tmp);
		}
		//按照文档数目多少降序排序
		int size = results.size();
		ClusterResult [] clusters = results.toArray(new ClusterResult[0]);
		for(int i=0;i<size;i++)
		{
			int max = i;
			for(int j=i+1;j<size;j++)
			{
				if(clusters[max].getDocs().size() < clusters[j].getDocs().size())
					max = j;
			}
			if(i != max)
			{
				ClusterResult tmp = clusters[i];
				clusters[i] = clusters[max];
				clusters[max] = tmp;
			}
		}
		return clusters;
	}
}
